package com.xzy.b;

import com.xzy.a.UserService;
import com.xzy.a.UserServiceImpl;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

/**
 * 说明：ApplicationContext与BeanFactory的关系
 *
 * @author xzy
 * @date 2021/11/29 21:36
 */
public class Main {
    /**
     * ApplicationContext继承自BeanFactory
     */
    public static void main(String[] args) {
        method1();
        method2();
    }

    private static void method1() {

        // 准备BeanDefinition
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(UserServiceImpl.class);

        // 通过BeanDefinition向BeanFactory注册Bean
        DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory();
        beanFactory.registerBeanDefinition("userServiceImpl", beanDefinition);

        // 通过BeanFactory获取Bean
        UserService bean1 = (UserService) beanFactory.getBean("userServiceImpl");
        UserService bean2 = beanFactory.getBean(UserService.class);
        System.out.println(bean1);
        System.out.println(bean2);
    }

    private static void method2() {
        // 准备BeanDefinition
        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition().getBeanDefinition();
        beanDefinition.setBeanClass(UserServiceImpl.class);

        // 通过BeanDefinition向通过ApplicationContext注册Bean
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        applicationContext.registerBeanDefinition("userServiceImpl", beanDefinition);
        applicationContext.refresh();

        // 通过ApplicationContext获取Bean
        UserService bean1 = (UserService) applicationContext.getBean("userServiceImpl");
        UserService bean2 = applicationContext.getBean(UserService.class);
        System.out.println(bean1);
        System.out.println(bean2);
    }
}
